package cn.fscode.code.generator.service.impl;

import cn.fscode.code.generator.mapper.GenerateHistoryMapper;
import cn.fscode.code.generator.model.po.GenerateHistoryPO;
import cn.fscode.code.generator.model.req.GeneratorReq;
import cn.fscode.code.generator.service.GenerateHistoryService;
import cn.fscode.commons.tool.core.exception.BizException;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author shenguangyang
 */
@Service
@RequiredArgsConstructor
public class GenerateHistoryServiceImpl implements GenerateHistoryService {
    private final GenerateHistoryMapper generateHistoryMapper;

    @Override
    @Transactional
    public void saveHistory(GeneratorReq req) {
        String content = JSON.toJSONString(req);
        String md5 = DigestUtils.md5DigestAsHex(content.getBytes(StandardCharsets.UTF_8));
        LambdaQueryWrapper<GenerateHistoryPO> wrapper = Wrappers.<GenerateHistoryPO>lambdaQuery()
                .eq(GenerateHistoryPO::getMd5Value, md5);
        GenerateHistoryPO history = generateHistoryMapper.selectOne(wrapper);
        if (history != null) {
            generateHistoryMapper.updateById(history);
            return;
        }
        GenerateHistoryPO generateHistoryPO = new GenerateHistoryPO();
        generateHistoryPO.setConfigContent(content);
        generateHistoryPO.setMd5Value(md5);
        generateHistoryMapper.insert(generateHistoryPO);
    }

    @Override
    public List<GenerateHistoryPO> listAll() {
        return generateHistoryMapper.selectList(new LambdaQueryWrapper<>());
    }

    @Override
    public GenerateHistoryPO getById(Long id) {
        return generateHistoryMapper.selectById(id);
    }

    @Override
    public void save(GenerateHistoryPO generateHistoryPO) {
        if (generateHistoryMapper.insert(generateHistoryPO) <= 0) {
            throw new BizException("保存失败");
        }
    }

    @Override
    public void update(GenerateHistoryPO generateHistoryPO) {
        if (generateHistoryMapper.updateById(generateHistoryPO) <= 0) {
            throw new BizException("更新失败");
        }
    }

    @Override
    public void delete(GenerateHistoryPO generateHistoryPO) {
        if (generateHistoryMapper.deleteById(generateHistoryPO) <= 0) {
            throw new BizException("删除失败");
        }
    }


}
